<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑商品</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        :root {
            --primary-color: #ffd700;
            --primary-light: #fff9e6;
            --text-color: #333;
            --border-color: #ffe066;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: Arial, sans-serif;
            background-color: var(--primary-light);
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid var(--border-color);
        }

        .header h1 {
            color: var(--text-color);
            font-size: 24px;
        }

        .back-btn {
            padding: 8px 16px;
            background-color: var(--primary-color);
            color: var(--text-color);
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .back-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 2px 8px rgba(255, 215, 0, 0.3);
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: var(--text-color);
            font-weight: 500;
        }

        .form-group input[type="text"],
        .form-group input[type="number"],
        .form-group select,
        .form-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            font-size: 14px;
            transition: all 0.3s;
        }

        .form-group input:focus,
        .form-group select:focus,
        .form-group textarea:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 2px rgba(255, 215, 0, 0.2);
        }

        .upload-section {
            border: 2px dashed var(--border-color);
            padding: 20px;
            text-align: center;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .upload-section:hover {
            border-color: var(--primary-color);
            background-color: var(--primary-light);
        }

        .upload-icon {
            font-size: 40px;
            color: var(--primary-color);
            margin-bottom: 10px;
        }

        .image-preview {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 20px;
        }

        .preview-item {
            position: relative;
            width: 100px;
            height: 100px;
        }

        .preview-item img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 4px;
        }

        .remove-image {
            position: absolute;
            top: -8px;
            right: -8px;
            background: #ff4444;
            color: white;
            border: none;
            border-radius: 50%;
            width: 20px;
            height: 20px;
            font-size: 12px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .submit-btn {
            background-color: var(--primary-color);
            color: var(--text-color);
            padding: 12px 24px;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            width: 100%;
            margin-top: 20px;
            transition: all 0.3s;
        }

        .submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 2px 8px rgba(255, 215, 0, 0.3);
        }

        .location-inputs {
            display: flex;
            gap: 10px;
        }

        .location-inputs select {
            flex: 1;
            padding: 10px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            font-size: 14px;
            transition: all 0.3s;
        }

        .location-inputs select:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 2px rgba(255, 215, 0, 0.2);
        }

        .location-inputs select:disabled {
            background-color: #f5f5f5;
            cursor: not-allowed;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <button class="back-btn" onclick="history.back()">
                <i class="fas fa-arrow-left"></i> 返回
            </button>
            <h1>编辑商品</h1>
            <div style="width: 80px;"></div>
        </div>

        <form id="productForm">
            <div class="form-group">
                <label for="productName">商品名称</label>
                <input type="text" id="productName" required>
            </div>

            <div class="form-group">
                <label for="price">价格</label>
                <input type="number" id="price" step="0.01" required>
            </div>

            <div class="form-group">
                <label for="shippingFee">运费</label>
                <input type="number" id="shippingFee" step="0.01" min="0" value="0">
            </div>

            <div class="form-group">
                <label for="brand">品牌</label>
                <input type="text" id="brand" placeholder="请输入品牌名称">
            </div>

            <div class="form-group location-group">
                <label>发货地</label>
                <div class="location-inputs">
                    <select id="province" required>
                        <option value="">请选择省份</option>
                    </select>
                    <select id="city" required disabled>
                        <option value="">请选择城市</option>
                    </select>
                    <select id="district" required disabled>
                        <option value="">请选择区县</option>
                    </select>
                </div>
            </div>

            <div class="form-group">
                <label for="category">商品分类</label>
                <select id="category" required>
                    <option value="">请选择分类</option>
                    <option value="1">电子产品</option>
                    <option value="2">图书教材</option>
                    <option value="3">服装饰品</option>
                    <option value="4">运动器材</option>
                    <option value="5">其他</option>
                </select>
            </div>

            <div class="form-group">
                <label for="condition">商品成色</label>
                <select id="condition" required>
                    <option value="">请选择成色</option>
                    <option value="5">全新</option>
                    <option value="4">几乎全新</option>
                    <option value="3">轻微使用</option>
                    <option value="2">明显使用</option>
                    <option value="1">重度使用</option>
                </select>
            </div>

            <div class="form-group">
                <label for="description">商品详情</label>
                <textarea id="description" rows="5" placeholder="请详细描述商品的使用情况、配件信息等"></textarea>
            </div>

            <div class="upload-section" onclick="document.getElementById('imageUpload').click()">
                <input type="file" id="imageUpload" hidden multiple accept="image/*">
                <i class="fas fa-cloud-upload-alt upload-icon"></i>
                <p>点击上传商品图片（最多6张）</p>
                <div class="image-preview" id="imagePreview"></div>
            </div>

            <button type="submit" class="submit-btn">
                <i class="fas fa-save"></i> 保存修改
            </button>
        </form>
    </div>

    <script>
        let productId = null;
        let imageUrls = [];
        let addressData = null;

        // 页面加载时获取商品信息和地址数据
        $(document).ready(function() {
            const urlParams = new URLSearchParams(window.location.search);
            productId = urlParams.get('id');
            
            // 先加载商品信息
            if (productId) {
                loadProductInfo(productId);
            }
            
            // 加载地址数据
            loadAddressData();
        });

        // 加载地址数据
        function loadAddressData() {
            // 模拟地址数据
            addressData = [
                {
                    code: "广东省",
                    name: "广东省",
                    cities: [
                        {
                            code: "深圳市",
                            name: "深圳市",
                            districts: [
                                { code: "罗湖区", name: "罗湖区" },
                                { code: "福田区", name: "福田区" },
                                { code: "南山区", name: "南山区" },
                                { code: "宝安区", name: "宝安区" },
                                { code: "龙岗区", name: "龙岗区" }
                            ]
                        },
                        {
                            code: "广州市",
                            name: "广州市",
                            districts: [
                                { code: "天河区", name: "天河区" },
                                { code: "海珠区", name: "海珠区" },
                                { code: "越秀区", name: "越秀区" }
                            ]
                        }
                    ]
                },
                {
                    code: "北京市",
                    name: "北京市",
                    cities: [
                        {
                            code: "北京市",
                            name: "北京市",
                            districts: [
                                { code: "朝阳区", name: "朝阳区" },
                                { code: "海淀区", name: "海淀区" },
                                { code: "东城区", name: "东城区" }
                            ]
                        }
                    ]
                }
            ];
            initProvinceSelect();
        }

        // 从商品信息中设置地址
        function setLocationFromProduct() {
            const location = JSON.parse(localStorage.getItem('tempLocation') || '{}');
            if (location.province) {
                $('#province').val(location.province);
                $('#province').trigger('change');
                
                if (location.city) {
                    setTimeout(() => {
                        $('#city').val(location.city);
                        $('#city').trigger('change');
                        
                        if (location.district) {
                            setTimeout(() => {
                                $('#district').val(location.district);
                            }, 100);
                        }
                    }, 100);
                }
            }
        }

        // 加载商品信息
        function loadProductInfo(id) {
            $.ajax({
                url: `/seller/product/detail?id=${id}`,
                type: 'GET',
                success: function(response) {
                    if (response.state === 1) {
                        const product = response.data;
                        // 填充基本信息
                        $('#productName').val(product.name || '');
                        $('#price').val(product.price || '');
                        $('#shippingFee').val(product.shippingFee || 0);
                        $('#brand').val(product.brand || '');
                        $('#category').val(product.categoryId || '');
                        $('#condition').val(product.conditionLevel || '');
                        $('#description').val(product.description || '');
                        
                        // 保存地址信息到localStorage
                        if (product.location) {
                            localStorage.setItem('tempLocation', product.location);
                            setLocationFromProduct();
                        }
                        
                        // 显示已有图片
                        try {
                            imageUrls = JSON.parse(product.images || '[]');
                            displayImages(imageUrls);
                        } catch (e) {
                            console.error('解析商品图片失败:', e);
                        }
                    } else {
                        alert('加载商品信息失败：' + response.msg);
                    }
                },
                error: function() {
                    alert('加载商品信息失败，请重试');
                }
            });
        }

        // 初始化省份下拉框
        function initProvinceSelect() {
            const provinceSelect = $('#province');
            provinceSelect.empty().append('<option value="">请选择省份</option>');
            
            addressData.forEach(province => {
                provinceSelect.append(`<option value="${province.code}">${province.name}</option>`);
            });
        }

        // 省份变更时更新城市
        $('#province').change(function() {
            const provinceCode = $(this).val();
            const citySelect = $('#city');
            const districtSelect = $('#district');
            
            citySelect.empty().append('<option value="">请选择城市</option>');
            districtSelect.empty().append('<option value="">请选择区县</option>');
            
            if (provinceCode) {
                const province = addressData.find(p => p.code === provinceCode);
                if (province && province.cities) {
                    province.cities.forEach(city => {
                        citySelect.append(`<option value="${city.code}">${city.name}</option>`);
                    });
                    citySelect.prop('disabled', false);
                }
            } else {
                citySelect.prop('disabled', true);
                districtSelect.prop('disabled', true);
            }
        });

        // 城市变更时更新区县
        $('#city').change(function() {
            const provinceCode = $('#province').val();
            const cityCode = $(this).val();
            const districtSelect = $('#district');
            
            districtSelect.empty().append('<option value="">请选择区县</option>');
            
            if (cityCode) {
                const province = addressData.find(p => p.code === provinceCode);
                if (province) {
                    const city = province.cities.find(c => c.code === cityCode);
                    if (city && city.districts) {
                        city.districts.forEach(district => {
                            districtSelect.append(`<option value="${district.code}">${district.name}</option>`);
                        });
                        districtSelect.prop('disabled', false);
                    }
                }
            } else {
                districtSelect.prop('disabled', true);
            }
        });

        // 处理图片上传
        $('#imageUpload').change(function() {
            const files = this.files;
            if (files.length + imageUrls.length > 6) {
                alert('最多只能上传6张图片');
                return;
            }

            for (let file of files) {
                const formData = new FormData();
                formData.append('file', file);

                $.ajax({
                    url: '/upload/image',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        if (response.state === 1) {
                            imageUrls.push(response.data);
                            displayImages(imageUrls);
                        } else {
                            alert('上传图片失败：' + response.msg);
                        }
                    },
                    error: function() {
                        alert('上传图片失败，请重试');
                    }
                });
            }
        });

        // 显示图片预览
        function displayImages(urls) {
            const preview = $('#imagePreview');
            preview.empty();
            
            urls.forEach((url, index) => {
                preview.append(`
                    <div class="preview-item">
                        <img src="${url}" alt="商品图片">
                        <button type="button" class="remove-image" onclick="removeImage(${index}, event)">
                            <i class="fas fa-times"></i>
                        </button>
                        ${index === 0 ? '<div class="cover-badge">封面</div>' : 
                        `<button type="button" class="set-cover" onclick="setCover(${index}, event)">
                            <i class="fas fa-star"></i> 设为封面
                        </button>`}
                    </div>
                `);
            });
        }

        // 设置封面图片
        function setCover(index, event) {
            event.stopPropagation(); // 阻止事件冒泡
            if (index === 0) return; // 已经是封面
            // 将选中的图片移到数组第一位
            const image = imageUrls.splice(index, 1)[0];
            imageUrls.unshift(image);
            displayImages(imageUrls);
        }

        // 删除图片
        function removeImage(index, event) {
            event.stopPropagation(); // 阻止事件冒泡
            imageUrls.splice(index, 1);
            displayImages(imageUrls);
        }

        // 添加封面图片的样式
        const style = document.createElement('style');
        style.textContent = `
            .preview-item {
                position: relative;
            }
            .cover-badge {
                position: absolute;
                top: 5px;
                left: 5px;
                background-color: var(--primary-color);
                color: var(--text-color);
                padding: 2px 6px;
                border-radius: 4px;
                font-size: 12px;
            }
            .set-cover {
                position: absolute;
                bottom: 5px;
                left: 5px;
                background-color: rgba(255, 215, 0, 0.8);
                color: var(--text-color);
                border: none;
                padding: 2px 6px;
                border-radius: 4px;
                font-size: 12px;
                cursor: pointer;
                display: flex;
                align-items: center;
                gap: 4px;
            }
            .set-cover:hover {
                background-color: var(--primary-color);
            }
        `;
        document.head.appendChild(style);

        // 提交表单
        $('#productForm').submit(function(e) {
            e.preventDefault();
            
            if (imageUrls.length === 0) {
                alert('请至少上传一张商品图片');
                return;
            }

            const productData = {
                id: productId,
                name: $('#productName').val().trim(),
                price: $('#price').val(),  // 保持原始字符串格式
                shippingFee: $('#shippingFee').val() || '0',  // 保持字符串格式
                brand: $('#brand').val().trim(),
                categoryId: $('#category').val(),  // 保持原始格式
                conditionLevel: $('#condition').val(),  // 保持原始格式
                description: $('#description').val().trim(),
                images: JSON.stringify(imageUrls),  // 修复图片数据的处理
                location: JSON.stringify({
                    province: $('#province').val(),
                    city: $('#city').val(),
                    district: $('#district').val()
                }),
                status: 1  // 添加状态字段
            };

            // 打印提交的数据，方便调试
            console.log('提交的数据:', productData);

            $.ajax({
                url: '/seller/product/update',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(productData),
                success: function(response) {
                    console.log('服务器响应:', response);  // 添加响应日志
                    if (response.state === 1) {
                        alert('修改成功！');
                        location.href = 'product-manage.html';
                    } else {
                        alert('修改失败：' + (response.msg || '未知错误'));
                    }
                },
                error: function(xhr, status, error) {
                    console.error('修改失败:', {
                        status: status,
                        error: error,
                        response: xhr.responseText
                    });
                    alert('修改失败，请检查网络连接或联系管理员');
                }
            });
        });
    </script>
</body>
</html> 